import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.Scanner;
import java.util.concurrent.CountDownLatch;

/**
 * @author bridge
 */
public class MultiThreadDownloadClient {
    public static void main(String[] args) throws FileNotFoundException {
        int threadSize;
        String[] taskList;
        Scanner scanner = new Scanner(new File("input.txt"));

        threadSize = scanner.nextInt();

        int taskListSize = scanner.nextInt();

        taskList = new String[taskListSize];
        for (int i = 0; i < taskListSize; i++) {
            taskList[i] = scanner.next();
        }

        long startTime = System.currentTimeMillis();
        for (int i = 0; i < taskListSize; i++) {
            CountDownLatch latch = new CountDownLatch(threadSize);
            MutiThreadDownLoad m = new MutiThreadDownLoad(threadSize, taskList[i], latch);
            System.out.println("开始下载第" + (i + 1) + "个文件");
            try {
                m.executeDownLoad();
                latch.await();
                Thread.sleep(1000);
                m.timer.cancel();
                long endTime = System.currentTimeMillis();
                int second = (int) ((endTime - startTime) / 1000);
                System.out.printf("已完成%d个文件,耗时%d分%d秒%n", i + 1, second / 60, second % 60);
                playSound();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("所有文件下载完成");
    }

    private static void playSound() {
        try {
            InputStream inputStream = MultiThreadDownloadClient.class.getClassLoader().getResourceAsStream("download-complete.wav");
            AudioStream audioStream = new AudioStream(inputStream);
            AudioPlayer.player.start(audioStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}